<?php 
/**
 * 单据模型
 * @author tangbl
 *
 */
class BillModel extends Model {

	/**
	 array(
 		0.字段名
		1.验证规则 [require 字段必须、email 邮箱、url URL地址、currency 货币、number 数字]
		2.提示信息  {%usr_form_validata_email_email}
		3.验证条件 [0.(默认)存在字段就验证;1.必须验证;2.值不为空的时候验证]
		4.附加规则 [regex、function、callback、confirm、equal、in、length、between、
		         expire、ip_allow、ip_deny、unique]
		5.验证时   [1.新增数据时候验证;2.编辑数据时候验证;3.(默认)全部情况下验证]
	  );
	 */
	protected $_validate=array(
		
	);
	
	/**
	 * 定义自动完成
	 */
	protected $_auto = array(
		array('addtime', 'time',     1,'function')
	);
	
	/**
	 * 数据库表名
	 * protected $tableName = 'bill';
	 */
	
	/**
	 * 分配单据到用户
	 * userid  旧用户id
	 * adminid 新用户id
	 */
	public function allotUser($map){
	
		$id   = $map['billid'];
		$rows = $this->find($id);
		$flag = false;
	
		if($rows['id']){
				
			$module = M("BillUser");
			$userid = $map['userid'];
			if($userid){
				$old  = array("billid"=>$id,"adminid"=>$userid);
				$user = $module->where($old)->find();
			}
				
			$adminid = $map['adminid'];
			$new     = array("billid"=>$id,"adminid"=>$adminid);
			$admin   = $module->where($new)->find();
				
			if($user['id']){
	
				$data = array("adminid"=>$adminid,"content"=>$map['content']);
				if($admin['id']){
					$data["id"] = $admin['id'];
				}else{
					$data["id"] = $user['id'];
				}
				$flag = $module->save($data);
			}else{
	
				if(empty($admin['id'])){
					$map['orderno'] = $rows["orderno"];
					$map['addtime'] = time();
					$flag = $module->add($map);
				}
			}
				
			if($flag){
				$map['title']   = $this->userTitle($adminid, $userid);
				$map['billid']  = $id;
				$map['dealno']  = $rows['dealno'];
				$this->addLog($map);
			}
		}
	
		return $flag;
	}
	
	/**
	 * 添加单据操作记录
	 */
	public function addLog($data){
		
		$data['addtime'] = time();
		return M("BillLog")->add($data);
	}
	
	/**
	 * 生成分配到门店操作标题
	 */
	public function userTitle($newid){
	
		$titile = "";
		$module = M("Admin");
		$user   = $module->find($newid);
		if($user['id']){
			$titile .= "单据分配到用户:";
			$titile .= $user['realname'].",编号:[".$user['id']."]";
		}
		return $titile;
	}
	
	/**
	 * 解挂操作
	 * @param  int  $billid 单据编号
	 */
	public function unlockOrder($billid){
		
		$bill   = $this->find($billid);
		
		$map['billid'] = $billid;

		$list   = M("BillDetail")->where($map)->select();
		$module = M("OrderCart");
		
		$where['tableid'] = $bill['tableid'];
		$where['dataid']  = $bill['dataid'];
		$where['company'] = $bill['company'];
		$pids = $module->where($where)->getField("pid", true);
		
		foreach ($list as $k=>$v){
			
			unset($v['id']);
			if( !in_array($v['pid'], $pids) ){
				$module->add($v);
			}
		}
		return $bill;
	}
	
}